package org.jboss.tools.examples.data;

import it.moda.component.dataorderer.Paginator;

import java.io.Serializable;
import java.util.List;

import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Produces;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ComponentSystemEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;

import org.jboss.tools.examples.model.Calendario;
import org.jboss.tools.examples.util.DataAccessController;

@ManagedBean
@SessionScoped
public class CalendarioPagedListProducer implements Serializable {
    public static final String NAV_LIST = "/admin/members/list";
    public static final String NAV_REDIRECT = "?faces-redirect=true";
    
    @Inject
    private EntityManager em;
    
    private List<Calendario> appuntamenti;
    
   
 
    private DataAccessController dataAccess = new DataAccessController();
    private DataModel dataModel;
    private int rowsPerPage = 5;
    private Calendario current;
    private int selectedItemIndex = -1;    
    private Paginator paginator;
    
    public void resetList() {
        dataModel = null;
    }
 
    public String prepareList() {
        resetList();
        return NAV_LIST + NAV_REDIRECT;
    }
 
    public void resetPagination(ComponentSystemEvent event) {
        paginator = null;
    }
 
    public Paginator getPaginator() {
        if (paginator == null) {
            paginator = new Paginator(rowsPerPage) {
 
                @Override
                public int getItemsCount() {
                    return dataAccess.count(Calendario.class,em);
                }
 
                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(dataAccess.findRange(Calendario.class, getPageFirstItem(), getPageFirstItem()+getPageSize(),em));
                }
            };
        }
 
        return paginator;
 
    }
    
//    @Produces
//   	@Named
//    public DataModel getAppuntamenti() {
//        if (dataModel == null) {
//            dataModel = getPaginator().createPageDataModel();
//        }
// 
//        return dataModel;
//    }
 
    public void next() {
        getPaginator().nextPage();
        resetList();
    }
 
    public void previous() {
        getPaginator().previousPage();
        resetList();
    }
}